<template>
	<cu-custom :isBack="true">
		<template #title>提交报告</template>
	</cu-custom>
	<view class="page-content">
		
		<view class="default-box theme-shadow mb-3">
			<view class="middle-text text-bold mb-3">上传报告</view>
			
			<view class="cu-form-group">
				<view class="grid col-3 grid-square flex-sub">
					<view class="bg-img" v-for="(item, index) in fileList" :key="index" @tap="viewFile(item)" :data-url="fileList[index]">
						<image :src="calcIcon(item.suffix)" mode="aspectFill" />
						<view class="file-name text-ellipsis-1">{{ item.filename }}</view>
						<view class="cu-tag bg-red" @tap.stop="delFile" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="chooseFile" v-if="fileList.length < 9">
						<text class='cuIcon-add'></text>
					</view>
				</view>
			</view>
		</view>
		
		<view v-if="false" class="text-in default-box theme-shadow" style="margin-bottom: 88rpx">
			<textarea
				:enable-native="false"
				placeholder="请输入文字"
				maxlength="500"
				cols="30"
				rows="10"
				style="height:200rpx"
				v-model="textarea"
			></textarea>
			<!-- #ifdef MP-ALIPAY -->
			<view class="voice-in" @click="navToVoice('totext')">
				<text class="cuIcon-voicefill text-gray"></text>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<ToText @updateText="updateText" />
			<!-- #endif -->
		</view>
		
		<view class="mb-4">
			<CuButton size="small" :disabled="submitDisable" @click="handleSubmit">提交</CuButton>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onLoad, onUnload } from "@dcloudio/uni-app"
import { ref, type Ref } from 'vue';
import CuButton from "@/components/CuButton.vue"
import { obj2str } from "@/utils/base"
import env from "@/env"
import store from "@/store/index.js"
import { voice2Text, downloadFile } from "@/utils/common"
import ToText from "@/components/ToText.vue"
import path from "path-browserify"
import { uploadFile } from "@/api/common.js"
import { router } from "@/router"
import { submitReport } from "@/api/mission.js"
// #ifdef H5
import dd from "gdt-jsapi"
// #endif

interface IFile {
	localPath: string
	serverPath: string
	suffix: string
	filename: string
}

const props = defineProps({
	mission_id: {
		type: String,
		default: ""
	}
})

let mission_id = null
let isSubmitLeave = false
let to_text_media_id = null
const fileList: Ref<IFile[]> = ref([] as IFile[])
const textarea: Ref<string> = ref("")
const submitDisable:Ref<boolean> = ref(false)
const viewFile = (file: any):void => {
	// #ifdef H5
	if (file.suffix === "docx") {
		router.push("/pages/index/word?title=" + file.filename + "&filepath=" + file.serverPath)
	}
	// #endif
}

const delFile= (e:any):void => {
	uni.showModal({
		title: '删除',
		content: '确定要删除这个文件？',
		cancelText: '取消',
		confirmText: '确认',
		success: res => {
			if (res.confirm) {
				fileList.value.splice(e.currentTarget.dataset.index, 1)
			}
		}
	})
}
const chooseFile = ():void => {
	dd.chooseFile({
		// "maxNum": 3,
		multiSelection: true
	}).then(async (res) => {
		uni.showLoading({
			title: "上传中"
		})
		try {
			for (let file of res.files) {
				const result = await uploadProcess(file.path)
				if (result.code === 200) {
					fileList.value.push({
						localPath: file.path,
						serverPath: result.url,
						suffix: result.originalFilename.match(/\.[^.]+$/g)[0].substring(1),
						filename: result.originalFilename,
					})
				}
			}
			uni.hideLoading()
		} catch (err) {
			uni.hideLoading()
		}
	}).catch((err) => {
		console.log(err)
	})
	// my.chooseFile().then(res => {
	//     console.log(res)
	// }).catch(err => {})
}

const calcIcon = (suffix:string):string => {
	if (suffix === 'docx') {
		return env.H5_RELATIVE_URL + '/static/images/docx_icon.png'
	} else {
		return env.H5_RELATIVE_URL + '/static/images/otherfile_icon.png'
	}
}

const uploadProcess = async (filePath:string = ""): Promise<any> => {
	let res = null
	// #ifdef MP-ALIPAY
	res = await uploadFile({
		filePath,
		name: path.basename(filePath)
	})
	// #endif
	// #ifdef H5
	const uploadRes = await dd.uploadFile({
		filePath: [ filePath ]
	})
	const result = await downloadFile({
		media_id: uploadRes[0],
		ext: filePath.match(/\.([0-9a-z]+)(?:[\?#]|$)/i)[1]
	})
	res = {
		code: 200,
		url: result.filepath,
		originalFilename: path.basename(filePath)
	}
	
	// #endif
	return res
}

const navToVoice = (recording_type) => {
	const query = obj2str({
		recording_type,
		callback: "/pages/mission/submitreport"
	})
	// console.log(`${env.DD_SCHEME}${env.DD_HOST}/action/open_app?type=1&offline=false&url=${encodeURIComponent(env.MINI_APP_URL + "pages/index/recording?" + query)}`)
	dd.openLink({
		url: `${env.DD_SCHEME}${env.DD_HOST}/action/open_app?type=1&offline=false&url=${encodeURIComponent(env.MINI_APP_URL + "pages/index/recording?" + query)}`
	}).then((res:any) => {
		console.log("success")
		console.log(res)
	}).catch((err:any) => {
		console.log("error")
		console.log(err)
	})
}

const updateText = (e: string) => {
	textarea.value = e
}

/**
 * 语音文件转文字
 */
const media2Text = ():void => {
	voice2Text(to_text_media_id)
		.then((res) => {
			textarea.value = res
		})
}

const handleSubmit = () => {
	if (!textarea.value && fileList.value.length === 0) {
		uni.showToast({
			icon: "none",
			title: "请至少提交一项材料"
		})
		return 
	}
	submitDisable.value = true
	uni.showLoading({
		title: "上传中"
	})
	
	const files = Array.from(fileList.value, (file) => ({ name: file.filename, url: file.serverPath }))
	submitReport({
		taskId: mission_id,
		files: files
	})
		.then(() => {
			uni.hideLoading()
			uni.showToast({
				icon: "success",
				title: "上传成功"
			})
			setTimeout(() => {
				isSubmitLeave = true
				router.back().catch((err) => {
					if (err.error === "already top of navigation") {
						router.replaceAll("/pages/mission/mission?mission_id=" + mission_id)
					}
				})
			}, 1000)
		})
}

onUnload(() => {
	if (!isSubmitLeave) {
		const mission_cache = {
			mission_id,
			textarea: textarea.value,
			fileList: fileList.value
		}
		uni.setStorageSync("submitreport_cache_data", JSON.stringify(mission_cache))
	}
})

onLoad(async (options) => {
	if (options.mission_id) {
		mission_id = options.mission_id
	}
	const query = await store.dispatch("getQuery")
	
	const cache_data = uni.getStorageSync("submitreport_cache_data")
	uni.removeStorage({ key: "submitreport_cache_data" })
	
	if (cache_data) {
		const mission_cache = JSON.parse(cache_data)
		if (!mission_id || mission_id == mission_cache.mission_id) {
			mission_id = mission_cache.mission_id
			if (query.recording_type === 'totext') {
				// 语音转文字
				to_text_media_id = query.mediaId
				media2Text()
			} else {
				textarea.value = mission_cache.textarea
			}
			fileList.value = mission_cache.fileList
		}
	} else if (query.mediaId) {
		// textarea.value += "out cachedata"
		uni.showToast({
			icon: "none",
			title: "缓存数据丢失！请联系管理员反馈问题"
		})
	}
})
</script>

<style lang="stylus" scoped>
.cu-form-group
	padding 0
.solids::after
	border 8rpx solid #3974df
.cuIcon-cameraadd, .cuIcon-add
	color #3974df!important

.text-in
	position: relative
	.voice-in
		position: absolute
		top: 46rpx
		right: 50rpx
		font-size 38rpx
		z-index: 99
		
.file-name
	position: absolute
	bottom: 0
	height: 20%
	text-align: center
	width: 100%
	color: #626262
</style>